from flask import Blueprint, request, session
from flask_restful import Api, Resource, marshal_with
from flask_restful.reqparse import RequestParser

from webapp.config import api_utils
from webapp.config.api_utils import oper_log, check_auth
from webapp.dto_mapper import exam_page_fields
from webapp.schema import ExamSchema
from webapp.service.exam_service import ExamInfoService

examinfo_app = Blueprint('examinfo', __name__, url_prefix='/api/examinfo')
examinfo_api = Api(examinfo_app)

parser = RequestParser()
parser.add_argument('id', location='json', type=int, trim=True, required=True)
parser.add_argument('sessionId', location='json', type=int, trim=False, required=False)
parser.add_argument('courseId', location='json', type=int, trim=False, required=False)
parser.add_argument('resourceId', location='json', type=int, trim=False, required=False)
parser.add_argument('ename', location='json', type=int, trim=True, required=False)
parser.add_argument('start', location='json', type=str, trim=False, required=False)
parser.add_argument('end', location='json', type=str, trim=False, required=False)
parser.add_argument('totaltime', location='json', type=int, trim=False, required=False)
parser.add_argument('score', location='json', type=int, trim=False, required=False)


@examinfo_api.resource("", "/")
class ExamInfoApi(Resource):
    @oper_log('查询所有考试', request)
    @check_auth('exam:list', request)
    @marshal_with(exam_page_fields)
    def get(self):
        params = request.args.items(multi=True)
        params_dict = api_utils.build_params(params)
        return ExamInfoService.query_all(**params_dict)

    @oper_log('新增考试', request)
    @check_auth('exam:add', request)
    def post(self):
        params = request.get_json()
        schema = ExamSchema()
        curr_exam = schema.load(params, unknown="exclude")
        user = session["user"]
        curr_exam.create_by = user["username"]
        ExamInfoService.create(curr_exam=curr_exam)

    @oper_log('删除课程', request)
    @check_auth('exam:del', request)
    def delete(self):
        ids = request.get_json()
        exam_set = set()
        for _id in ids:
            exam_set.add(ExamInfoService.find_by_id(id=_id))
        ExamInfoService.delete(exam_set=exam_set)

    @oper_log('修改课程', request)
    @check_auth('exam:edit', request)
    def put(self):
        # parser_put = parser.copy()
        # parser_put.parse_args()
        params = request.get_json()
        schema = ExamSchema()
        curr_exam = schema.load(params, unknown="exclude")
        user = session["user"]
        curr_exam.update_by = user["username"]
        ExamInfoService.update(curr_exam=curr_exam)
